use std::sync::Arc;

use axum::Router;
use sea_orm::{Database, DatabaseConnection};
use tracing::info;

use crate::{
    config::{self, server_config::ServerConfig},
    router,
};
pub struct AppState {
    pub db: DatabaseConnection,
}

pub async fn run() {
    info!("App正在启动...");
    let ServerConfig {
        port,
        db_username,
        db_password,
    } = config::server_config::init_server_config();

    info!("正在连接数据库...");
    let db = Database::connect(format!(
        "mysql://{}:{}@localhost:3306/db01",
        db_username, db_password
    ))
    .await
    .map_err(|e| {
        tracing::error!("数据库连接失败!");
        e
    })
    .unwrap();

    let app_state = Arc::new(AppState { db });

    let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{}", port))
        .await
        .map_err(|e| {
            tracing::error!("{}端口监听失败!", port);
            e
        })
        .unwrap();

    let router = Router::new().nest("/api", router::init_router(&app_state));
    tracing::info!("服务启动在: http://127.0.0.1:{}", port);
    if let Err(_) = axum::serve(listener, router).await {
        tracing::error!("服务启动失败!")
    }
}
